<?php
/**
 * oscshop2 B2C电子商务系统
 *
 * ==========================================================================
 * @link      http://www.oscshop.cn/
 * @copyright Copyright (c) 2015-2017 oscshop.cn. 
 * @license   http://www.oscshop.cn/license.html License
 * ==========================================================================
 *
 * @author    
 *
 * 余额   api接口
 * 2017-03-11
 */
namespace osc\common\service;

use think\Db;


class Predeposit{
	
	//余额充值
	function recharge($uid,$pay_code,$money){
		
		if(!is_numeric($money)){				
			return array('error'=>'请输入数字');
		}			
		//负数
		if($money<0){
			return array('error'=>'充值金额不能是负数');
		}
		if($money<config('predeposit_num')){
			return array('error'=>'充值金额最少为'.config('predeposit_num').'元');
		}
		$data['uid']=$uid;
		$username=member('username');
		$data['username']=empty($username)?member('nickname'):$username;
		$data['order_num_alias']=build_order_no();
		$data['money']=$money;
		$data['description']='余额充值';
		$data['prefix']=1;
		$data['payment_code']=$pay_code;
		$data['pay_status']=0;
		$data['creat_time']=time();
		
		$id=Db::name('predeposit')->insert($data,false,true);
		
		return array(
			'pay_order_no'=>$data['order_num_alias'],
			'subject'=>'余额充值'.$money,
			'pay_total'=>$money,
			'id'=>$id
		);
	}
	//更新充值订单
	function update_recharge_order($id,$uid,$money){
		Db::name('predeposit')->where('p_id',$id)->update(array('pay_status'=>1,'pay_time'=>time()));
		Db::name('member')->where('uid',$uid)->setInc('predeposit',$money);
	}
	
	private function validate($data){
		
		$uid=$data['uid'];
		
		if(!$uid){
			return ['error'=>'请先登录'];
		}
		
		$cart=osc_cart();
		
		if(!$cart->count_cart_total($uid,$data['type'])) {	
			return ['error'=>'您的购物车没有商品'];	
		}
		
		$city_id=$data['city_id'];		
		
		$shipping=$cart->has_shipping($uid,$data['type']);
		//配送验证
		if(isset($shipping['error'])){			
			return ['error'=>$shipping['error']];
		}
		
		//需要配送的
		if($shipping){
			if($city_id==''){
				return ['error'=>'请选择收货地址'];
			}
		}
		
		// 验证商品数量		
		$cart_list=Db::name('cart')->where(array('uid'=>$uid,'type'=>$data['type']))->select();
		
		foreach ($cart_list as $k => $v) {
			
			$param['option']=json_decode($v['goods_option'], true);
			$param['goods_id']=$v['goods_id'];
			$param['quantity']=$v['quantity'];
			
			//判断商品是否存在，验证最小起订量   		
	   		if($error=$cart->check_minimum($param)){   			
	   			return $error;			
	   		}			
					
			//验证商品数量和必选项
			if($error=$cart->check_quantity($param)){			
				return $error;
			}
			
		}
		return [
			'uid'=>$uid,
			'city_id'=>$city_id,
			'shipping'=>$shipping
		];
	}
	//计算商品总价(默认类型为普通商品)
	function calcul_total($uid,$city_id,$type,$shipping_method){
		$goods=osc_cart()->get_all_goods($uid,$type);
		$total_all_price=0;
		$weight = 0;
		if(!empty($goods)){
			foreach ($goods as $k => $v) {
				$total_all_price+=$v['total'];
				if ($v['shipping']&&$v['free_shipping']==0) {
					$weight += osc_weight()->convert($v['weight'], $v['weight_class_id'],config('weight_id'));
				}
			}
		}
		
		//总价达到免运费额度
		if($total_all_price>=config('free_shipping')){
			$weight=0;
		}
		
		$t=osc_transport()->calc_transport($shipping_method,$weight,$city_id);

		return array(
			'total'=>$t['price']+$total_all_price,
			'weight'=>$weight
		);

	}
	
	//余额支付
	function pay($data){
		if(request()->isPost()){
			$uid=is_login();

			//购物车验证
			$result=$this->validate($data);
			
			if(isset($result['error'])){
				return $result;
			}

			$calcul=$this->calcul_total($result['uid'],$result['city_id'],$data['type'],$data['shipping_method']);

			//需要配送的
			if($result['shipping']){								
				$weight =$calcul['weight'];
				$order['shipping_method']=$data['shipping_method'];		
			}else{
				$weight=0;
				$order['shipping_method']='';
			}

			//通证消费
			if($data['apply'] == 1){
				//平台、服务中心商品
				if($data['type'] != 2){

					if($calcul['total'] > member('card')){
						return array('error'=>'通证不足,剩余'.member('card'));
					}

					$order['payment_method']='card';
				}

				//报单商品
				if($data['type'] == 2){
					$card = $calcul['total']*0.3;
					$activation = $calcul['total']*0.7;

					if($card > member('card')){
						return array('error'=>'通证不足,剩余'.member('card'));
					}

					if($activation > member('activation')){
						return array('error'=>'激活积分不足,剩余'.member('activation'));
					}

					$order['payment_method']='card+activation';
				}
			}

			//消费积分消费
			if($data['apply'] == 2){
				if($data['type'] != 2){

					if($calcul['total'] > member('integrals')){
						return array('error'=>'消费积分不足,剩余'.member('integrals'));
					}

					$order['payment_method']='integrals';
				}
			}

			$order['shipping_address_id']=$data['address_id']; 

			$order['weight']=$weight;
			$order['shipping_city_id']=$result['city_id'];
			$order['comment']=$data['comment'];
			$order['uid']=$result['uid'];
			$order['username']=$data['username'];

			//查询商品是否赠送积分
			$goods = Db::name('goods')->where('goods_id',$data['goods_id'])->find();
			//查询会员等级
			$user_state = member('user_state');
			$points = 0;
			if($user_state == 1)
			{
				$points = $goods['points'];
			}
			elseif($user_state == 2)
			{
				$points = $goods['points']*2;
			}
			elseif($user_state == 3)
			{
				$points = $goods['points']*4;
			}
			elseif($user_state == 4)
			{
				$points = $goods['points']*5;
			}

//			print_r($points);
//			exit;
			//开始事务
			try
			{
				Db::startTrans();

				//写入订单
				$order = osc_order()->add_order($data['apply'],$order);
				//清空购物车
				osc_order()->clear_cart($order['uid']);
				//更新订单，订单历史，积分，商品数量
				osc_order()->update_order($order['order_id']);

				$username=$data['username'];

				$username=empty($username)?member('nickname'):$username;

				//推荐奖
				//$r= osc_service('common','Sttl')->recomm_bonus($calcul['total'],$order['order_id']);

				//更新余额
				$user_order_info = array(
						'uid'=>$result['uid'],
						'username'=>$username,
						'order_id'=>$order['order_id'],
						'order_num_alias'=>$order['pay_order_no'],
						'total'=>$calcul['total'],
						'apply'=>$data['apply'],
						'type'=>$data['type'],
						'points'=>$points,
				);
				$this->update_predeposit($user_order_info);

				//结束事务
				Db::commit();

			} catch (\Exception $e) {

				Db::rollbacke();
			}

			
		}
	}
	
	//更新余额
	function update_predeposit($order){

		$user = Db::name('member')->where('uid',$order['uid'])->find();

		$map = array(
			'uid'=>$order['uid'],
			'username'=>$order['username'],
			'order_id'=>$order['order_id'],
			'order_num_alias'=>$order['order_num_alias'],
			'money'=>$order['total'],
			'pay_type' => $order['apply'],
			'prefix'=>2,
			'creat_time'=>time(),
			'pay_time'=>time(),
			'pay_status'=>1
		);
		//通证消费
		if($order['apply'] == 1){
			if($order['type'] != 2){
				$befor = (int)$user['card'];
				$after = (int)$user['card'] - $order['total'];
				$map['description']= '购买商品,购买前通证数'.$befor.' 购买后通证数'.$after;

				Db::name('member')->where('uid',$order['uid'])->dec('card',$order['total'])->inc('score',$order['points'])->update();
			}else{
				$befor_card = (int)$user['card'];
				$after_card = (int)$user['card'] - $order['total']*0.3;

				$befor = (int)$user['activation'];
				$after = (int)$user['activation'] - $order['total']*0.7;

				$map['description']= '购买商品,购买前通证数'.$befor_card.'、激活积分数'.$befor.'，购买后通证数'.$after_card.'、激活积分数'.$after;

				Db::name('member')->where('uid',$order['uid'])->dec('card',$order['total']*0.3)->dec('activation',$order['total']*0.7)->inc('score',$order['points'])->update();
			}

		}
		//消费积分消费
		if($order['apply'] == 2){
			$befor = (int)$user['integrals'];
			$after = (int)$user['integrals'] - $order['total'];
			$map['description']= '购买商品,购买前消费积分数'.$befor.' 购买后前消费积分数'.$after;

			Db::name('member')->where('uid',$order['uid'])->dec('integrals',$order['total'])->inc('score',$order['points'])->update();
		}


		Db::name('predeposit')->insert($map);

	}

}